package com.sx.micowell.module

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.view.Gravity
import android.view.KeyEvent
import android.view.MenuItem
import android.view.WindowManager
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.mvvm.base.BaseFragment
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.ActivityManager
import com.example.mvvm.until.DeviceIdUtil
import com.example.mvvm.until.SPUtils
import com.example.mvvm.until.Tips
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ImmersionBar
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.ActMainBinding
import com.sx.micowell.framework.app.MyActivity
import com.sx.micowell.framework.app.SPKey
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.entity.event.RefreshTrainEvent
import com.sx.micowell.framework.model.MainModel
import com.sx.micowell.framework.tools.AppDialogUtils
import com.sx.micowell.framework.tools.DisplayUtils
import com.sx.micowell.framework.tools.LocationUtils
import kotlinx.android.synthetic.main.act_main.*
import java.util.*

@Route(path = RoutePath.MAIN)
class MainActivity : MyActivity<ActMainBinding>(),
    BottomNavigationView.OnNavigationItemSelectedListener {

    private lateinit var baseFragments: List<BaseFragment<*>>

    private var viewModel: MainModel? = null

    override fun getDataBindingConfig(): DataBindingConfig =
        DataBindingConfig(R.layout.act_main, BR.viewModel, viewModel)

    override fun initViewModel() {
        super.initViewModel()
        viewModel = getActivityScopeViewModel(MainModel::class.java)
    }

    override fun initView() {
        main_navigation.itemIconTintList = null
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(true).init()
        main_navigation.setOnNavigationItemSelectedListener(this)
    }


    override fun initData() {
        //初始化页面
        baseFragments = listOf(
            RouteManager.getInstance().getHomeFragment(this),
            RouteManager.getInstance().getPlanFragment(this),
            RouteManager.getInstance().getTrainFragment(this),
            RouteManager.getInstance().getMineFragment(this)
        )
        HANDLER.post { onFragmentChangeSelected(0) }
        requestPermissionsIfAboveM()
        RouteManager.getInstance().intentSportActivity()
    }

    override fun onDestroy() {
        super.onDestroy()
        LocationUtils.getInstance(this).removeLocationUpdatesListener()
    }

    override fun initViewObservable() {
        super.initViewObservable()

        viewModel?.loginInvalidEvent?.observe(this, {
            AppDialogUtils.showTipDialog(
                context, "提示", "登录已过期，请重新登录",
                object : AppDialogUtils.IOnClickListener {
                    override fun leftListener() {}
                    override fun rightListener() {
                        viewModel?.loginPopMap?.clear()
                        SPUtils.getInstance().put(SPKey.SP_TOKEN, "")
                        SPUtils.getInstance().put(SPKey.SP_PHONE, "")
                        RouteManager.getInstance().intentLogin()
                        finish()
                    }
                })
        })

        viewModel?.isAuthEvent?.observe(this, {
            AppDialogUtils.showBasicDialog(
                context, "提示", "请完善个人信息",
                object : AppDialogUtils.IOnClickListener {
                    override fun leftListener() {}
                    override fun rightListener() {
                        RouteManager.getInstance().intentToSexAge()
                    }
                })
        })

        viewModel?.locationEvent?.observe(this) {
            viewModel?.checkLocation(it.longitude.toString(), it.latitude.toString())
        }

        viewModel?.driverError?.observe(this) {
            if (dialogBuilder == null) {
                showBasicDialog(context, "提示", "你的设备超出距离，请联系售后人员")
            }

        }
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_home -> {
                //首页
                onFragmentChangeSelected(0)
            }
            R.id.action_plan -> {
                //计划
                onFragmentChangeSelected(1)
            }
            R.id.action_train -> {
                //训练
                RxBus.getDefault().post(RefreshTrainEvent())
                onFragmentChangeSelected(2)
            }
            R.id.action_mine -> {
                //我的
                onFragmentChangeSelected(3)
            }
        }

        return true
    }


    private var baseFragment: BaseFragment<*>? = null

    fun onFragmentChangeSelected(position: Int) {
        val fragmentManager = this.supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        for (i in baseFragments.indices) {
            val tempFragment: BaseFragment<*> = baseFragments.get(i)
            if (position == i) {
                if (tempFragment.isAdded) {
                    if (baseFragment == null) {
                        baseFragment = tempFragment
                    }
                    transaction.hide(baseFragment!!).show(tempFragment).commitAllowingStateLoss()
                } else {
                    if (baseFragment == null) {
                        baseFragment = tempFragment
                        transaction.add(R.id.nav_host_fragment, baseFragment!!)
                            .commitAllowingStateLoss()
                    } else {
                        transaction.hide(baseFragment!!).add(R.id.nav_host_fragment, tempFragment)
                            .commitAllowingStateLoss()
                    }
                }
                baseFragment = tempFragment
                break
            }
        }
    }

    private val REQUEST_CODE_PERMISSION = 1
    private val permissionHintMap: MutableMap<String, String?> = HashMap()
    private fun requestPermissionsIfAboveM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val requiredPermissions: MutableMap<String, String> = HashMap()
            requiredPermissions[Manifest.permission.ACCESS_FINE_LOCATION] = "定位"
            requiredPermissions[Manifest.permission.WRITE_EXTERNAL_STORAGE] = "存储"
            requiredPermissions[Manifest.permission.READ_PHONE_STATE] = "设备信息"
            for (permission in requiredPermissions.keys) {
                if (checkSelfPermission(permission) !== PackageManager.PERMISSION_GRANTED) {
                    permissionHintMap[permission] = requiredPermissions[permission]
                }
            }
            if (!permissionHintMap.isEmpty()) {
                requestPermissions(
                    permissionHintMap.keys.toTypedArray(),
                    REQUEST_CODE_PERMISSION
                )
            } else {
                if (api26Gps()) {
                    viewModel?.uuid= DeviceIdUtil.getDeviceId(this)
                    LocationUtils.getInstance(this)
                } else {
                    requestPermissions(
                        permissionHintMap.keys.toTypedArray(),
                        REQUEST_CODE_PERMISSION
                    )
                }
            }
        }
    }

    fun api26Gps(): Boolean {
        permissionHintMap.clear()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val api26BackGroupGps: MutableMap<String, String> = HashMap()
            api26BackGroupGps[Manifest.permission.ACCESS_BACKGROUND_LOCATION] = "始终允许定位"
            for (permission in api26BackGroupGps.keys) {
                if (checkSelfPermission(permission) !== PackageManager.PERMISSION_GRANTED) {
                    permissionHintMap[permission] = api26BackGroupGps[permission]
                }
            }
        }
        return permissionHintMap.size == 0
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val failPermissions: MutableList<String> = LinkedList()
        for (i in grantResults.indices) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                failPermissions.add(permissions[i])
            }
        }
        if (!failPermissions.isEmpty()) {
            val sb = StringBuilder()
            for (permission in failPermissions) {
                sb.append(permissionHintMap[permission]).append("、")
            }
            sb.deleteCharAt(sb.length - 1)
            val hint = "未授予必要权限: " +
                    sb.toString() +
                    "，请前往设置页面开启权限"
            AlertDialog.Builder(this)
                .setMessage(hint)
                .setNegativeButton(
                    "取消"
                ) { dialog, which -> System.exit(0) }.setPositiveButton(
                    "设置"
                ) { dialog, which ->
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                    System.exit(0)
                }.show()
        } else {
            val api26Gps = api26Gps()
            if (api26Gps) {
                viewModel?.uuid= DeviceIdUtil.getDeviceId(this)
                LocationUtils.getInstance(this)
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    requestPermissions(
                        permissionHintMap.keys.toTypedArray(),
                        REQUEST_CODE_PERMISSION
                    )
                }
            }
        }
    }

    /**
     * 连续按两次返回键就退出
     */
    private var keyBackClickCount = 0


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            when (keyBackClickCount++) {
                0 -> {
                    Tips.show(this, "再点一次退出")
                    val timer = Timer()
                    timer.schedule(object : TimerTask() {
                        override fun run() {
                            keyBackClickCount = 0
                        }
                    }, 3000)
                }
                1 -> {
                    ActivityManager.getInstance().exit()
                    finish()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    var dialogBuilder: AlertDialog.Builder? = null

    /**
     * 基础对话框
     * @param context
     */
    fun showBasicDialog(
        context: Context,
        title: String?,
        content: String?
    ) {
        dialogBuilder = AlertDialog.Builder(context, R.style.customTransparentDialog)
        dialogBuilder!!.setCancelable(true)
        val dialogView =
            (context as Activity).layoutInflater.inflate(R.layout.dialog_location, null)
        // 标题
        val titleView = dialogView.findViewById<TextView>(R.id.txt_title)
        titleView.text = title
        // 内容
        val contentView = dialogView.findViewById<TextView>(R.id.txt_message)
        contentView.text = content
        dialogView.findViewById<TextView>(R.id.txt_confirm)
            .setOnClickListener {
                System.exit(0)
            }
        dialogBuilder!!.setView(dialogView)
        val alertDialog = dialogBuilder!!.create()
        alertDialog.window!!.setGravity(Gravity.CENTER)
        alertDialog.show()
        alertDialog.setCancelable(false)
        alertDialog.setCanceledOnTouchOutside(false)

        //设置大小
        val layoutParams = alertDialog.window!!.attributes
        layoutParams.width = 4 * DisplayUtils.getScreenWidth(context) / 4
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
        alertDialog.window!!.attributes = layoutParams
    }
}